﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using APMS.WebSite.Common;
using APMS.WebSite.Models.DataStore;
using APMS.WebSite.Models.ViewData.Pages;
using System.Collections.Generic;

namespace APMS.WebSite.Controllers
{
    /// <summary>
    /// TodoController controls all Views related to ToDo operation which are:
    /// * Index (/InProject/{projectId}/Todo/)
    /// * List (/InProject/{projectId}/Todo/List)
    /// * Create (/InProject/{projectId}/Todo/Create)
    /// * Update (/InProject/{projectId}/Todo/Update/{id})
    /// * View (/InProject/{projectId}/Todo/View/{id})
    /// * Delete (/InProject/{projectId}/Todo/Delete/{id})
    /// * MORE
    /// </summary>
    /// <version>$Revision$ $Date$</version>
    /// <history>
    /// <record>09/15/2008. raQuiam - Created this file</record>
    /// </history>
    [HandleError]
    public class TodoController : ProjectBaseController
    {
        #region Keys for ViewData
        /// <summary>
        /// Use in method List
        /// </summary>
        public const string ALL_TODOS = "AllTodos";

        public const string ALL_TODO_ITEMS = "AllTodoItems";
        #endregion

        #region List Action
         /// <summary>
        /// List all Todo under target project 
        /// </summary>
        /// <returns></returns>
        public ActionResult List(int projectId)
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction(MainNavItemType.ToDo);
            if (exception != null)
                return exception;

            // Get current project
            Project currentProject = base.GetProject(projectId);

            // Set Window Title
            base.SetTitle(currentProject.ProjectName + " | All To-do", true);
            base.SetInfoToUserControls(currentProject);

            // TODO: Query
            // Query all todo under current project
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from todo in db.ToDo
                where
                    todo.ProjectID == currentProject.ProjectID
                orderby todo.ModifyDate descending
                select todo;

            // Query all todo-item
            var query2 =
                from todoItem in db.ToDoItem
                orderby todoItem.ModifyDate descending
                select todoItem;

            ViewData[CURRENT_PROJECT] = currentProject;
            ViewData[ALL_TODOS] = query.ToList();
            ViewData[ALL_TODO_ITEMS] = query2.ToList();


            return View("List");
        }
        #endregion

        #region Create Action
         /// <summary>
        /// Create new Message
        /// </summary>
        /// <returns></returns>
        public ActionResult Create(int projectId)
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction(MainNavItemType.ToDo);
            if (exception != null)
                return exception;

            // Get current project
            Project currentProject = base.GetProject(projectId);

            // Set Window Title
            base.SetTitle(currentProject.ProjectName + " | Create New Todo", true);
            base.SetInfoToUserControls(currentProject);

            // Prepare ViewData
            ManageTodoViewData viewData = new ManageTodoViewData();
            viewData.CurrentProject = currentProject;

            // If POST means UPDATE the value from Request.Form to DB
            // If GET means VIEW the value from DB
            if (Request.HttpMethod == Constants.HttpMethod.POST)
            {
                #region Create new record in DB

                #region Extract values from Form
                string todoName = Request.Form["todoName"];

                #endregion

                // Prepare to INSERT by Linq
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();

                ToDo todo = new ToDo();
                todo.ProjectID = projectId;
                todo.UserName = UserProfile.UserName;
                todo.ToDoName = todoName;
                todo.AddDate = DateTime.Now;
                todo.ModifyDate = DateTime.Now;

                db.ToDo.InsertOnSubmit(todo);
                db.SubmitChanges();

                // Fill the rest of viewData
                viewData.CurrentTodo = todo;
                //viewData.IsCurrentMessageUpdate = true;

                // Redirect to  Project Overview
                return RedirectToAction("View", new { projectId = projectId, todo.ToDoID });
                #endregion
            }
            //else
            //{
            //    viewData.IsCurrentMessageUpdate = false;
            //}

            return View("Create", viewData);
        }
        #endregion

        #region View/Update Actions
        public ActionResult View(int projectId, int id)
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction(MainNavItemType.ToDo);
            if (exception != null)
                return exception;

            // Get current project
            Project currentProject = base.GetProject(projectId);
            base.SetInfoToUserControls(currentProject);

            // Prepare ViewData
            ManageTodoViewData viewData = new ManageTodoViewData();
            viewData.CurrentProject = currentProject;

            // If GET means VIEW the value from DB
            // Support only GET
            if (Request.HttpMethod == Constants.HttpMethod.GET)
            {
                // Query specify message under current project
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
                var query =
                    from todo in db.ToDo
                    where
                        todo.ProjectID == currentProject.ProjectID &&
                        todo.ToDoID == id
                    orderby todo.ModifyDate descending
                    select todo;

                // Query all todo-item
                var query2 =
                    from todoItem in db.ToDoItem
                    where 
                        todoItem.ToDoID == id
                    orderby todoItem.ModifyDate descending
                    select todoItem;

                // Make sure the target message is still existed
                if (query.Count() > 0)
                {
                    // Prepare ViewData
                    viewData.CurrentTodo = query.First();
                    viewData.ToDoItems = query2.ToList();

                    // Set Window Title
                    base.SetTitle(currentProject.ProjectName + " | " + viewData.CurrentTodo.ToDoName, true);
                }
                else
                {
                    throw new ApplicationException("Target Todo is no longer existed");
                }

                //viewData.IsCurrentMessageUpdate = false;
            }

            return View("View", viewData);
        }

        /// <summary>
        /// Callback Action
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="id"></param>
        public void Update(int projectId, int id)
        {
            // If POST means UPDATE the value from Request.Form to DB
            // If GET means VIEW the value from DB
            if (Request.HttpMethod == Constants.HttpMethod.POST)
            {
                #region Create new record in DB

                #region Extract values from Form
                string todoName = Request.Form["todoName"];
                #endregion

                // Query specify message under current project
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
                var query =
                    from todo in db.ToDo
                    where
                        todo.ProjectID == projectId &&
                        todo.ToDoID == id
                    select todo;

                // Make sure the target message is still existed
                if (query.Count() > 0)
                {
                    ToDo item = query.First();
                    item.ToDoName = todoName;
                    item.ModifyDate = DateTime.Now;

                    db.SubmitChanges();
                }

                #endregion

                Response.Write("success");
            }
        }
        #endregion

        #region Delete Action
        public ActionResult Delete(int projectId, int id)
        {
            // Query specify message under current project
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from todo in db.ToDo
                where
                    todo.ProjectID == projectId &&
                    todo.ToDoID == id
                orderby todo.ModifyDate descending
                select todo;

            // Make sure the target message is still existed
            if (query.Count() > 0)
            {
                // Read value from DB
                ToDo item = query.First();

                db.ToDo.DeleteOnSubmit(item);
                db.SubmitChanges();
            }
            else
            {
                throw new ApplicationException("Todo is no longer existed");
            }

            // Redirect to  List Messages
            return RedirectToAction("List", new { projectId = projectId });
        }
        #endregion

        #region Add Item Action
        public ActionResult AddItem(int projectId, int id)
        {
            if (Request.HttpMethod == Constants.HttpMethod.GET)
            {
                #region Create new record in DB

                // Prepare to INSERT by Linq
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();

                ToDoItem item = new ToDoItem();
                item.ToDoID = id;
                item.ToDoItemDetail = "Untitled";
                item.AddDate = DateTime.Now;
                item.ModifyDate = DateTime.Now;
                item.AssignBy = UserProfile.UserName;
                item.AssignTo = UserProfile.UserName;
                item.DeathLine = DateTime.Now.AddDays(5);

                db.ToDoItem.InsertOnSubmit(item);
                db.SubmitChanges();

                
                #endregion
            }

            // Redirect to  Project Overview
            return RedirectToAction("View", new { projectId = projectId, id = id });
        }
        #endregion

        #region Update Item Action
        public void UpdateItem(int projectId, int id)
        {
            // If POST means UPDATE the value from Request.Form to DB
            // If GET means VIEW the value from DB
            if (Request.HttpMethod == Constants.HttpMethod.POST)
            {
                #region Create new record in DB

                #region Extract values from Form
                int todoItemId = Convert.ToInt32(Request.Form["todoItemId"]);
                string todoItemValue = Request.Form["todoItemValue"];
                bool isDone = false;
                #endregion

                // Query specify message under current project
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
                var query =
                    from todoItem in db.ToDoItem
                    where
                        todoItem.ToDoID == id &&
                        todoItem.ToDoItemID == todoItemId
                    select todoItem;

                // Make sure the target message is still existed
                if (query.Count() > 0)
                {
                    ToDoItem item = query.First();
                    item.ToDoItemDetail = todoItemValue;
                    item.ModifyDate = DateTime.Now;

                    db.SubmitChanges();
                }

                #endregion

                Response.Write("success");
            }
        }
        #endregion

        #region From OAT
        ////"Project",      // Route name
        //public ActionResult create(int projectId, String todo_name)
        //{
        //    //throw new NotImplementedException();   
        //    String username = "admin";
        //    MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
        //    ToDo newToDo = new ToDo();
        //    newToDo.ProjectID = projectId;
        //    newToDo.ToDoName = todo_name;
        //    newToDo.UserName = username;
        //    newToDo.ModifyDate = DateTime.Now;
        //    newToDo.AddDate = DateTime.Now;


        //    db.ToDo.Add(newToDo);
        //    db.SubmitChanges();
        //    return View("test");
        //}

        //public ActionResult Delete(int projectId, int id)
        //{
        //    //throw new NotImplementedException();
        //    MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();


        //    try
        //    {
        //        ToDo deleteToDo = db.ToDo.Single(p => p.ToDoID == id);
        //        db.ToDo.Remove(deleteToDo);
        //        db.SubmitChanges();
        //    }
        //    catch (InvalidOperationException ex)
        //    {
        //        System.Console.WriteLine("called on set with zero items");
        //    }
        //    ////////////////////// DELETE DATA


        //    return View("test");
        //}



        //public ActionResult Update(int projectId, int id)
        //{
        //    // Initialize data required by master page

        //    ActionResult exception = base.InitializeAction();
        //    if (exception != null)
        //        return exception;

        //    // Ser Window Title
        //    base.SetTitle("To Do | " + id);

        //    // SELECT * FROM user WHERE user.UserName = '{currentUser}'
        //    MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
        //    var query =
        //        from todo in db.ToDo
        //        where
        //            todo.ToDoID == id
        //        select todo;

        //    // Prepare ViewData
        //    ManageTodoViewData viewData = new ManageTodoViewData();
        //    viewData.CurrentTodo = query.First<ToDo>();

        //    //TODO: Handle both POST and GET methods
        //    if (Request.HttpMethod == Constants.HttpMethod.POST)
        //    {
        //        // If POST means UPDATE the value from Request.Form to DB
        //        // If GET means VIEW the value from DB
        //        #region Update record back to DB
        //        viewData.CurrentTodo.ToDoName = Request.Form["ToDoName"];
        //        viewData.CurrentTodo.ModifyDate = DateTime.Now;
        //        viewData.IsCurrentTodoUpdate = true;

        //        db.SubmitChanges();
        //        #endregion
        //    }
        //    else
        //    {
        //        viewData.IsCurrentTodoUpdate = false;
        //    }

        //    return View("Update", viewData);
        //}
        #endregion

    }
}
